package com.witsoft.manager;


import com.alibaba.fastjson.JSONObject;
import com.witsoft.device.model.third.DeviceProductRateBO;
import com.witsoft.device.utils.DateUtil;
import com.witsoft.device.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 调用第三方接口api
 */

@Slf4j
@Component
public class FeignManager {

    @Autowired
    private RestTemplate template;

    @Value("${gongli.mes.host}")
    private String host;

    @Value("${gongli.mes.bad-product-count-api}")
    private String badProductCountApi;

    @Value("${gongli.mes.performance-rate-api}")
    private String performanceApi;

    @Value("${gongli.mes.sign}")
    private String sign;


    /**
     * @desc 根据设备编号获取不合格产品数
     * @return
     */
    public Map<String, String> getBadProductCountByDevice(String deviceCodes){

        Map<String, String> datas = new HashMap<>();
        String url = host + badProductCountApi + "?deviceName={0}&sign={1}";
        url = MessageFormat.format(url, deviceCodes, sign);
        log.info("#### mes 调用查询api：{}", JSONObject.toJSONString(url));

        try{
            Result result = template.getForObject(url, Result.class);
            log.info("#### mes 调用查询设备不合格数结果：{}", JSONObject.toJSONString(result));

            if(result.getCode() == 200){
                List data = (List) result.getData();
                data.forEach(e ->{
                    DeviceProductRateBO rateInfo = JSONObject.parseObject(JSONObject.toJSONString(e), DeviceProductRateBO.class);
                    datas.put(rateInfo.getAcCode(), rateInfo.getFailQuantity().toString());
                });
            }
        }catch (Exception e){
            log.error("调用mes接口获取不合格品数异常：{}", e.getMessage());
        }

        return datas;
    }



    /**
     * @desc 通过mes获取当年每月的节拍数和报工数乘积    -->性能开动率计算公式，产品节拍数 * 报工数 / 总的运行时间
     * @param deviceCodes：
     * @param start：
     * @param end：
     * @param type: day 或month
     */
    public Map getBeatMultiplyWorkReportOfYear(String deviceCodes) {

        StringBuffer timeRanges = new StringBuffer();
        try{
            for (int i = 1; i <= 12; i++) {
                Long firstDayOfMonth = DateUtil.getFirstDayTimeStampOfMonth(i);
                Long lastDayTimeStampOfMonth = DateUtil.getLastDayTimeStampOfMonth(i);

                timeRanges.append(firstDayOfMonth).append("-").append(lastDayTimeStampOfMonth).append(",");
            }
        }catch (Exception e){
            log.error("### 日期处理异常：{}", e.getMessage());
            timeRanges.append("0").append("-").append("31").append(",");
        }


        String timeRangesStr = timeRanges.substring(0, timeRanges.length() - 1);
        String url = host + performanceApi + "?deviceCodes="+deviceCodes +"&timeRange=" + timeRangesStr +"&sign=" + sign +"&timeType=month";

        Result result = template.getForObject(url, Result.class);
        log.info("#### mes 调用结果：{}", JSONObject.toJSONString(result));

        if(result.getCode() == 200){
            Map data = (Map) result.getData();
            return data;
        }


        return new HashMap<>();
    }



    /**
     * @desc 通过mes获取每日的节拍数和报工数乘积    -->性能开动率计算公式，产品节拍数 * 报工数 / 总的运行时间
     * @param deviceCode：
     * @param start：
     * @param end：
     * @param type: day 或month
     */
    public Map<String, Double> getBeatMultiplyWorkReportOfDay(String deviceCodes, Date start, Date end, String type) {

        try{
            String timeRangeParam = start.getTime() + "-" +end.getTime();
            String url = host + performanceApi + "?deviceCodes="+deviceCodes +"&timeRange=" + timeRangeParam +"&sign=" + sign +"&timeType=" + type;

            Result result = template.getForObject(url, Result.class);
            log.info("#### mes 调用结果：{}", JSONObject.toJSONString(result));

            if(result.getCode() == 200){
                Map<String, Double> data = (Map<String, Double>) result.getData();
                return data;
            }
        }catch (Exception e){
            log.error("### mes api调用失败：{}", e.getMessage());
        }

        return new HashMap<>();
    }
}
